// map.js
//导入位置服务sdk
import qqMap from '../../../utils/qqmap'
Page({
  data: {
    latitude: 40.060539,
    longitude: 116.343847,
    markers: [
      {
        id: 1,
        latitude: 40.22077,
        longitude: 116.23128,
        width: 24,
        height: 30,
      },
      {
        id: 2,
        latitude: 40.225905,
        longitude: 116.23318799999998,
        width: 40,
        height: 40,
        iconPath: '/static/images/marker.png',
      },
    ],
    repairDetail: {},
    polyline: [],
  },
  onLoad({ id }) {
    // 获取报修详情的数据
    this.getRepairDetail(id)
    this.getPolyline()
  },
  // 报修详情接口
  async getRepairDetail(id) {
    if (!id) return wx.utils.toast('参数有误!')
    // 调用接口
    const { code, data: repairDetail } = await wx.http.get('/repair/' + id)
    // 检测接口是否调用成功
    if (code !== 10000) return wx.utils.toast()
    // 渲染数据
    this.setData({ repairDetail })
  },
  //调用位置服务(路线规划)
  getPolyline() {
    qqMap.direction({
      mode: 'driving',
      from: '40.227978,116.22998',
      to: '40.22077,116.23128',
      success: (result, routes) => {
        console.log('路线规划成功', result, routes)
        // 检查路线数据是否存在
        if (!routes || !routes[0] || !routes[0].polyline) {
          console.error('路线规划数据异常', routes)
          return
        }
        const coors = routes[0].polyline
        const points = []
        //坐标解压（返回的点串坐标，通过前向差分进行压缩）
        for (let i = 2; i < coors.length; i++) {
          coors[i] = Number(coors[i - 2]) + Number(coors[i]) / 1000000
        }
        // 获取经纬度
        for (let i = 0; i < coors.length; i += 2) {
          points.push({ latitude: coors[i], longitude: coors[i + 1] })
        }
        console.log('生成路线点数量', points.length)
        // 使用中间点作为地图中心
        const centerIndex = Math.floor(points.length / 2)
        // 渲染数据
        this.setData({
          latitude: points[centerIndex].latitude,
          longitude: points[centerIndex].longitude,
          polyline: [{ points, color: '#5591af', width: 4 }],
        })
      },
      fail: (err) => {
        console.error('路线规划失败', err)
      },
    })
  },
  editRepair(ev){
    wx.navigateTo({
      url: '/repair_pkg/pages/form/index?id='+ev.mark.id,
    })
  }
})
